<template>
  <div>
    <div class="contract-list-page">
      <!-- 导航栏 -->
      <CommonHeader
        v-if="isAdd"
        :header-obj="{
          title: $t('合同创建'),
          rightText: $t('合同创建'),
          leftText: '',
        }"
        show-left-arrow
        @left-click="handleBack"
        @right-click="handleCreate"
      />
      <CommonHeader
        v-else
        :header-obj="{ title: $t('合同创建'), rightText: '', leftText: '' }"
        show-left-arrow
        @left-click="handleBack"
        @right-click="handleCreate"
      />

      <!-- 搜索栏 -->
      <van-search
        v-model="searchKeyword"
        :placeholder="$t('请输入客户名称、编码、订单编号等搜索')"
        @search="handleSearch"
        class="search-bar"
      />

      <!-- 筛选栏 -->
      <van-tabs
        v-model="activeTab"
        @change="handleTabChange"
        class="filter-tabs"
      >
        <van-tab :title="$t('全部')" name="-1" />
        <van-tab :title="$t('待审核')" name="0" />
        <van-tab :title="$t('审核中')" name="4" />
        <van-tab :title="$t('未通过')" name="2" />
        <van-tab :title="$t('已通过')" name="1" />
      </van-tabs>
      <!-- 时间 -->
      <div class="chose-time">
        <van-popover
          v-model="showPopover"
          trigger="click"
          placement="left"
          :actions="actions"
          @select="onSelect"
        >
          <template #reference>
            <span>{{ timeText }} <van-icon name="arrow" /></span>
          </template>
        </van-popover>
      </div>

      <!-- 合同列表 -->
      <pull-refresh-list
        ref="pullRefreshList"
        :fetch-data="fetchContractList"
        :initial-params="params"
        :page-size="10"
      >
        <div slot-scope="{ item, index }" class="review-container">
          <div @click="handleContractClick(item)">
            <div class="header">
              <div class="title">{{ item.contractNumber }}</div>
              <div :class="getStatusClass(item.formState)">
                {{ statusMap[item.formState] }}
              </div>
            </div>
            <div class="review-content">
              <div class="info-row">
                <div class="label">{{ $t('评审单号') }}</div>
                <div class="value">{{ item.judgeNumber }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('客户') }}</div>
                <div class="value">{{ item.signTarget }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('签约主体') }}</div>
                <div class="value">{{ item.signSubject }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('提交时间') }}</div>
                <div class="value">{{ item.createdTime }}</div>
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <button
              class="copy-btn"
              v-if="[0, 1, 2, 3].includes(+item.formState)"
              @click="handleCopy(item)"
              v-permission="['HTCJ-COPY']"
            >
              {{ $t('复制') }}
            </button>
            <template v-if="item.formState != 1">
              <button
                class="reject-btn"
                v-if="[0].includes(item.formState) && item.oaFlag == 0"
                v-permission="['HTCJ-REJECT']"
                @click="handleReject(item)"
              >
                {{ $t('驳回') }}
              </button>
              <button
                class="approve-btn"
                v-if="[0].includes(item.formState) && item.oaFlag == 0"
                v-permission="['HTCJ-PASS']"
                @click="handleApprove(item)"
              >
                {{ $t('通过') }}
              </button>
              <button
                class="delete-btn"
                v-if="[0, 2, 3].includes(item.formState)"
                @click="handleDelete(item)"
                v-permission="['HTCJ-DEL']"
              >
                {{ $t('删除') }}
              </button>
            </template>
          </div>
        </div>
      </pull-refresh-list>
    </div>

    <!-- 日期选择器 -->
    <van-popup v-model="showDatePickerPopup" position="bottom">
      <van-calendar
        v-model="showDatePickerPopup"
        :min-date="minDate"
        :max-date="maxDate"
        type="range"
        @confirm="onDateConfirm"
        @cancel="showDatePickerPopup = false"
      />
    </van-popup>
    <!-- min -->
    <CustomActionSheet
      :modelValue="show"
      :title="actionText"
      :confirm-text="$t('确认')"
      :cancel-text="$t('取消')"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      :showFooter="true"
    >
      <template #content>
        <div class="reject-content" v-if="actionText == $t('确认驳回？')">
          <p><i class="re-red">*</i>{{ $t('驳回原因') }}</p>
          <van-field
            v-model="rejectReason"
            type="textarea"
            :placeholder="$t('请输入驳回原因')"
            label-align="top"
            :auto-height="true"
          />
        </div>
        <div style="height: 100px" v-else></div>
      </template>
    </CustomActionSheet>
    <!-- temp -->
    <CustomActionSheet
      :modelValue="tempShow"
      :title="$t('合同模板')"
      :confirm-text="$t('确认')"
      :cancel-text="$t('取消')"
      @confirm="handleConfirmTemp"
      @cancel="handleCancelTemp"
      :showFooter="true"
    >
      <template #content>
        <!-- 搜索栏 -->
        <van-search
          v-model="tempKeyword"
          :placeholder="$t('请输入模板名称或编码')"
          @search="onTempSearch"
          class="search-bar"
        />
        <div class="temp-scroll">
          <van-radio-group v-model="tempChecked">
            <div class="check-box">
              <van-radio :name="item" v-for="(item, i) in tempList" :key="i">
                <div class="check-box-r">
                  <p>{{ $t('模版名称 ') }}{{ item.definitionStr }}</p>
                  <p>{{ $t('模版类型 ') }}{{ item.templateTypeStr }}</p>
                </div>
              </van-radio>
            </div>
          </van-radio-group>
          <van-pagination
            v-model="currentPage"
            :page-count="tempPages.total"
            mode="simple"
            @change="onPageChange"
          />
        </div>
      </template>
    </CustomActionSheet>
  </div>
</template>
<script>
import {
  getContractList,
  auditPass,
  auditReject,
  deleteContract,
  getContractTemplateList,
  contractPreVerification,
} from '@/api/contract'
import CustomActionSheet from '@/components/CustomActionSheet.vue'
import CommonHeader from '@/components/CommonHeader.vue'
import PullRefreshList from '@/components/PullRefreshList.vue'
import { mapGetters } from 'vuex'
import { Toast, Dialog } from 'vant'
import dayjs from 'dayjs'

export default {
  name: 'CreateList',
  components: {
    CustomActionSheet,
    CommonHeader,
    PullRefreshList,
  },
  data() {
    return {
      // 状态定义
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(2025, 11, 31),
      // 响应式数据
      showDatePickerPopup: false,
      timeText: this.$t('全部时间'),
      show: false,
      actionText: '',
      itemObj: '',
      rejectReason: '',
      tempShow: false,
      tempKeyword: '', // 模板关键词
      tempChecked: null, // 模板选中
      tempList: [],
      currentPage: 1,
      tempPages: {
        nowPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 状态筛选映射
      statusMap: {
        0: this.$t('待审核'),
        1: this.$t('已通过'),
        2: this.$t('已驳回'),
        3: this.$t('审核中'),
      },
      activeTab: '-1',
      searchKeyword: '',
      showPopover: false,
      actions: [
        { text: this.$t('全部时间') },
        { text: this.$t('近一个月') },
        { text: this.$t('近三个月') },
        { text: this.$t('近半年') },
        { text: this.$t('自定义时间') },
      ],
      // 列表参数
      params: {
        formState: null,
        keyword: '',
        startTime: null,
        endTime: null,
        sort: 'DESC',
      },
      isAdd: false,
    }
  },
  created() {
    console.log('[  this.permissionSet.some(item => item == "HTCJ-ADD") ]-164')
    this.isAdd = this.permissionSet.some((item) => item == 'HTCJ-ADD')
  },
  watch: {
    searchKeyword(val) {
      this.params.keyword = val
      this.$refs.pullRefreshList.onRefresh()
    },
  },
  computed: {
    ...mapGetters('user', ['permissionSet']),
  },
  methods: {
    fetchContractList() {
      return new Promise((resolve, reject) => {
        getContractList(this.params).then((res) => {
          resolve(res)
        })
      })
    },
    getTempList() {
      return new Promise((resolve, reject) => {
        getContractTemplateList({
          nowPage: this.tempPages.nowPage,
          pageSize: this.tempPages.pageSize,
          keyword: this.tempKeyword,
        })
          .then((res) => {
            this.tempList = res.rootArray
            this.tempPages.total = res.totalPage
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    handleBack() {
      console.log('[ handleBack ]-173', 111)
      this.$router.go(-1)
    },

    handleSearch() {
      this.$refs.pullRefreshList.onRefresh()
    },

    handleTabChange(v) {
      console.log('[ v ]-215', v)
      // 创建新对象以触发参数变化检测
      let params = {}
      if (v == 1) {
        // 已通过 用其他参数
        params = {
          ...this.params,
          formState: null,
          auditPass: 1,
        }
      } else {
        params = {
          ...this.params,
          auditPass: 0,
          formState: v === '-1' ? null : v,
        }
      }
      this.params = params

      this.$refs.pullRefreshList.onRefresh()
    },

    // 合同点击
    handleContractClick(row) {
      this.$router.push({
        path: '/contract/detail',
        query: {
          formId: row.formId,
          definitionId: row.definitionId,
          definitionCode: row.definitionCode,
          judgeNumber: row.judgeNumber,
          contractSource: 0,
          formQuery: true,
          readonly: true,
          formState: 3,
          oaFlag: 1,
        },
      })
    },
    handleCopy(row) {
      this.$router.push({
        path: '/contract/contractCopy',
        query: {
          formId: row.formId,
          definitionId: row.definitionId,
          definitionCode: row.definitionCode,
          copy: true,
          pageFrom: 'add',
        },
      })
    },

    // 合同创建
    handleCreate() {
      this.getTempList().then(() => {
        this.tempShow = true
      })
    },

    // 模板搜索
    onTempSearch() {
      this.getTempList()
    },

    onPageChange(page) {
      this.params.nowPage = page
      this.currentPage = page
    },

    // 时间选择
    onSelect({ text }) {
      console.log('[ text ]-205', text)
      switch (text) {
        case this.$t('全部时间'):
          this.params.startTime = null
          this.params.endTime = null
          this.timeText = this.$t('全部时间')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近一个月'):
          this.params.startTime = dayjs()
            .subtract(1, 'month')
            .format('YYYY-MM-DD')
          this.params.endTime = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近一个月')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近三个月'):
          this.params.startTime = dayjs()
            .subtract(3, 'month')
            .format('YYYY-MM-DD')
          this.params.endTime = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近三个月')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近半年'):
          this.params.startTime = dayjs()
            .subtract(6, 'month')
            .format('YYYY-MM-DD')
          this.params.endTime = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近半年')
          this.$refs.pullRefreshList.onRefresh()
          break
        default:
          this.showDatePickerPopup = true
          break
      }
    },

    // 日期选择器确认
    onDateConfirm(value) {
      if (value && value.length === 2) {
        const startDate = dayjs(value[0]).format('YYYY-MM-DD')
        const endDate = dayjs(value[1]).format('YYYY-MM-DD')
        this.params.startTime = startDate
        this.params.endTime = endDate
        this.timeText = this.$t('{startDate} 至 {endDate}', {
          startDate: startDate,
          endDate: endDate,
        })

        this.showDatePickerPopup = false
      }
      this.fetchContractList(true)
    },

    // 删除
    handleDelete(item) {
      Dialog.confirm({
        title: this.$t('提示'),
        message: this.$t('确认删除合同吗？'),
      })
        .then(() => {
          deleteContract({
            formId: item.formId || '',
          }).then((res) => {
            Toast(this.$t('删除成功'))
            this.fetchContractList(true)
          })
        })
        .catch(() => {
          // on cancel
        })
    },

    // 通过
    handleApprove(item) {
      this.itemObj = item
      this.actionText = this.$t('确认通过合同？')
      this.show = true
    },

    // 驳回
    handleReject(item) {
      this.itemObj = item
      this.actionText = this.$t('确认驳回？')
      this.show = true
    },

    // 自定义面板事件处理
    handleConfirm() {
      if (this.actionText === this.$t('确认通过合同？')) {
        auditPass({
          formId: this.itemObj?.formId || '',
        }).then((res) => {
          Toast(this.$t('通过成功'))
          this.fetchContractList(true)
          this.show = false
        })
      } else {
        if (!this.rejectReason) {
          Toast(this.$t('请输入驳回原因'))
          return
        }
        auditReject({
          formId: this.itemObj.formId || '',
          examineOpinion: this.rejectReason,
        }).then((res) => {
          Toast(this.$t('驳回成功'))
          this.fetchContractList(true)
          this.show = false
        })
      }
    },

    handleCancel() {
      this.show = false
    },

    handleConfirmTemp() {
      if (!this.tempChecked) {
        Toast(this.$t('请选择模板'))
        return
      }
      let params = {
        checkSource: 1,
        templateId: this.tempChecked.templateId,
        definitionId: this.tempChecked.definitionId,
      }
      contractPreVerification(params).then((res) => {
        if (res.data.resultCode == '0000') {
          this.$router.push({
            path: '/contract/createForm',
            query: {
              definitionId: this.tempChecked.definitionId,
              definitionCode: this.tempChecked.definitionCode,
              pageFrom: 'add',
            },
          })
        }
      })
      // this.$router.push({
      //   path: '/contract/createForm',
      //   query: {
      //     templateId: this.tempChecked.templateId,
      //     definitionId: 24,
      //     definitionCode: 'WHQYSJ',
      //     pageFrom: 'add'
      //   }
      // })
    },

    handleCancelTemp() {
      this.tempShow = false
    },

    getStatusClass(status) {
      switch (status) {
        case 1:
          return 'status-completed'
        case 2:
          return 'status-reject'
        case 3:
          return 'status-expired'
        case 0:
          return 'status-processing'
        default:
          return 'status'
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.reject-content {
  padding: 0 16px 100px 16px;
  font-size: 14px;
}
.re-red {
  font-style: normal;
  color: red;
  font-size: 14px;
}
.chose-time {
  color: #666666;
  line-height: 21px;
  text-align: right;
  font-style: normal;
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  span {
    height: 21px;
    display: flex;
    font-weight: 400;
    font-size: 15px;
    align-items: center;
  }
}

.contract-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 10px;
  background-color: #fff;
}

.filter-tabs {
  background-color: #fff;
}

.contract-list {
  background-color: #f5f5f5;
  padding: 10px;
}
.review-container {
  margin: 0 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background: #fff;
  margin-top: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px;
}

.title {
  font-weight: 500;
  font-size: 16px;
  color: #333333;
  line-height: 23px;
  text-align: left;
  font-style: normal;
}

.status {
  color: #fe890f;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.review-content {
  padding: 0 16px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
}

.label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding: 0 16px;
  margin-bottom: 10px;
}

button {
  padding: 8px 16px;
  margin-left: 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  background: transparent;
  display: flex;
  align-items: center;
}

.reject-btn {
  width: 60px;
  height: 26px;
  border-radius: 15px;
  border: 1px solid #fec39e;
  color: #ff8512;
}

.approve-btn {
  width: 60px;
  height: 26px;
  border-radius: 15px;
  border: 1px solid #a5abff;
  color: #5762f4;
}

.delete-btn {
  width: 60px;
  height: 26px;
  border-radius: 15px;
  border: 1px solid #eb5353;
  color: #ec1111;
}

button:hover {
  opacity: 0.8;
}
.status-tag {
  padding: 2px 8px;
  border-radius: 12px;
}
.status-processing {
  color: #fe890f;
  font-size: 16px;
}

.status-completed {
  color: #23c176;
  font-size: 16px;
}

.status-reject {
  color: #f83232;
  font-size: 16px;
}
.check-box-r {
  font-size: 13px;
  color: #333333;
}
.check-box {
  .van-radio {
    height: 60px;
    background: #f6f7fd;
    border-radius: 6px;
    margin: 10px 10px 0 10px;
    padding-left: 10px;
  }
}
.temp-scroll {
  height: 60vh;
  overflow-y: scroll;
  padding-bottom: 100px;
}
.copy-btn {
  height: 26px;
  border-radius: 15px;
  border: 1px solid #5762f4;
  color: #5762f4;
}
</style>
